package com.example.controller;

import com.example.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {


    @Value("${meituan002.path}")
    private  String path;

    //图片上传
   @PostMapping("/upload")
    public R<String> upload(MultipartFile file)
   {
       //获取原始文件名字
       String originalFilename = file.getOriginalFilename();
       //截取后缀
       String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        //UUID重新生成文件名
       String fileName = UUID.randomUUID().toString() + suffix;
       //判断文件夹是否存在
       File dir=new File(path);
       if(!dir.exists()) {
           dir.mkdirs();//允许创建多重文件夹
       }
       try {
           file.transferTo(new File(path+fileName));
       } catch (IOException e) {
           e.printStackTrace();
       }
       //记得把文件名返回回去
       return R.success(fileName);
   }


   //下载
    @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response)
    {
        log.info(name);
        //输入流读取文件内容
        try {
            FileInputStream fileInputStream=new FileInputStream(new File(path+name));
            //输出流将文件写回浏览器；
            ServletOutputStream outputStream=response.getOutputStream();
            //设置响应回去的是什么类型的文件
            response.setContentType("image/png");
            byte[] bytes=new byte[1024];
            int length=0;
            while((length= fileInputStream.read(bytes))!=-1)
            {
                outputStream.write(bytes,0,length);
                //刷新
                outputStream.flush();
            }
            //关闭输入输出流
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
